package com.flyone.fuxiao.controller;

import com.flyone.fuxiao.common.BaseResponse;
import com.flyone.fuxiao.common.ResultUtils;
import com.flyone.fuxiao.model.dto.gpt.ChatHistoryAddRequest;
import com.flyone.fuxiao.model.dto.gpt.GptAddRequest;
import com.flyone.fuxiao.service.ChatHistoryService;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: text-to-picture
 * @ClassName: GptController
 * @description: GPT控制接口
 * @author: banyun
 * @create: 2024-04-01 10:45
 */


@RestController
@Api(tags = "GPT控制接口")
@Slf4j
@RequestMapping("/gpt")
public class ChatController {

    @Resource
    private ChatHistoryService chatHistoryService;

    @PostMapping("/generate")
    @ApiOperation(value = "生成文本")
    @CrossOrigin
    public void generateText(@RequestBody GptAddRequest gptAddRequest,
                             HttpServletResponse response,
                             HttpServletRequest request) {
        response.setHeader("Content-Type", "text/event-stream");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("utf-8");
        // 生成文本流，返回给前端，前端通过事件流接收，实现实时展示
        Flowable<String> gptVOFlowable = chatHistoryService.generateTextByFlyone(gptAddRequest, response, request);
        try {
            // 订阅流，将流返回给前端
            Disposable complete = gptVOFlowable.subscribe(streamResponse -> {
                        // 将数据写入response
                        response.getWriter().write(streamResponse);
                        // 每次写完数据后，需要flush一下，否则数据不会返回给前端
                        response.getWriter().flush();
                    },
                    // 异常处理
                    Throwable::printStackTrace,
                    // 完成后的回调
                    () -> System.out.println("complete")
            );
            complete.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/save")
    public BaseResponse<String> saveChatHistory(@RequestParam("token") String token,
                                                @RequestBody ChatHistoryAddRequest chatHistoryAddRequest,
                                                HttpServletRequest request) {
        // 保存聊天记录
        String r_token = chatHistoryService.saveChatHistory(token, chatHistoryAddRequest, request);
        return ResultUtils.success(r_token);
    }
}
//curl -H "Accept:text/event-stream" http://localhost:8081/gpt/generateStream?input=圆的周期律为什么大于3.2&model=gpt-3.5-turbo